package com.wolfword.crawler.server.service.impl;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.wolfword.common.exception.CrawlException;
import com.wolfword.crawler.server.dao.CrawlerDao;
import com.wolfword.crawler.server.service.CrawlerService;

@Service
public class CrawlerServiceImpl implements CrawlerService {
	
	Logger logger = LoggerFactory.getLogger(CrawlerServiceImpl.class);
	
	@Autowired
	private CrawlerDao crawlerDao;
	@Value("${html.store.path}")
	private String crawlStorageFolder;

	/**
	 * 获取未爬取的根域名
	 */
	@Transactional
	@Override
	public Map<String, Object> getRootUrl() {

		Map<String, Object> map = null;
		try {
			map = crawlerDao.getRootUrl();
			if (map == null)
				return null;
			// 将此域名信息更新为已分配
			System.out.println("server map:" + map);
			System.out.println("server root_url_id：" + map.get("root_url_id"));
			System.out.println("server url：" + map.get("url"));
			crawlerDao.updateRootUrl(String.valueOf(map.get("url")), 1);
		} catch (Exception e) {
			logger.error("获取未爬取根域名异常", e);
			throw new CrawlException("获取未爬取根域名异常");
		}
		return map;
	}

	@Override
	public String statisticUrl(String url) {
		String message = null;
		// 将根域名信息更改为抓取完成状态2
		try {
			crawlerDao.updateRootUrl(url, 2);
			// 获取url的root_url_id
			long root_url_id = crawlerDao.queryRootUrlId(url);
			// 统计子网页信息
			crawlerDao.statisticUrl((int) root_url_id);
			// 更新parent_url_id
			crawlerDao.updateParentUrlId((int) root_url_id);
			message = "统计成功";
		} catch (Exception e) {
			logger.error("统计子网页信息异常", e);
			throw new CrawlException("统计子网页信息异常");
		}
		return message;
	}
}
